<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        #messageContainer {
            border: 1px solid #ccc;
            padding: 10px;
            margin: 10px 0;
            height: 300px;
            overflow-y: auto;
        }
        .message {
            margin: 5px 0;
            padding: 5px;
            background-color: #f0f0f0;
        }
        .input-container {
            margin: 10px 0;
        }
        input[type="text"] {
            padding: 5px;
            margin-right: 5px;
        }
        .message-input {
            width: 60%;
        }
        .client-input {
            width: 100px;
        }
        button {
            padding: 5px 10px;
            margin-left: 5px;
        }
        #clientIdDisplay {
            margin: 10px 0;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>SSE Message Demo</h1>
    <div id="clientIdDisplay"></div>
    <div id="messageContainer"></div>
    <div class="input-container">
        <input type="text" id="messageInput" class="message-input" placeholder="Enter your message">
        <input type="text" id="targetClientId" class="client-input" placeholder="Target ID">
        <button onclick="sendDirectMessage()">Send Direct</button>
        <button onclick="broadcast()">Broadcast</button>
    </div>

    <script>
        const messageContainer = document.getElementById('messageContainer');
        const messageInput = document.getElementById('messageInput');
        const targetClientInput = document.getElementById('targetClientId');
        const clientIdDisplay = document.getElementById('clientIdDisplay');
        
        // Generate a random client ID
        const clientId = 'client-' + Math.random().toString(36).substr(2, 9);
        clientIdDisplay.textContent = 'Your Client ID: ' + clientId;
        
        // 连接到SSE服务器
        const eventSource = new EventSource(`http://localhost:8080/subscribe/${clientId}`);
        
        // 处理连接成功消息
        eventSource.addEventListener('INIT', function(event) {
            addMessage('System: ' + event.data);
        });
        
        // 处理收到的消息
        eventSource.addEventListener('MESSAGE', function(event) {
            addMessage('Received: ' + event.data);
        });
        
        // 处理错误
        eventSource.onerror = function(error) {
            console.error('SSE Error:', error);
            addMessage('Error: Connection lost. Trying to reconnect...');
        };
        
        // 发送点对点消息
        function sendDirectMessage() {
            const message = messageInput.value;
            const targetId = targetClientInput.value;
            if (message.trim() && targetId.trim()) {
                fetch(`http://localhost:8080/send/${targetId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'text/plain',
                    },
                    body: message
                })
                .then(() => {
                    messageInput.value = '';
                    addMessage(`Sent to ${targetId}: ${message}`);
                })
                .catch(error => {
                    console.error('Error sending message:', error);
                    addMessage('Error: Failed to send message');
                });
            }
        }
        
        // 广播消息
        function broadcast() {
            const message = messageInput.value;
            if (message.trim()) {
                fetch('http://localhost:8080/broadcast', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'text/plain',
                    },
                    body: message
                })
                .then(() => {
                    messageInput.value = '';
                    addMessage(`Broadcast: ${message}`);
                })
                .catch(error => {
                    console.error('Error broadcasting message:', error);
                    addMessage('Error: Failed to broadcast message');
                });
            }
        }
        
        // 添加消息到界面
        function addMessage(message) {
            const messageElement = document.createElement('div');
            messageElement.className = 'message';
            messageElement.textContent = message;
            messageContainer.appendChild(messageElement);
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
        
        // 支持按回车发送消息
        messageInput.addEventListener('keypress', function(event) {
            if (event.key === 'Enter') {
                if (targetClientInput.value.trim()) {
                    sendDirectMessage();
                } else {
                    broadcast();
                }
            }
        });
    </script>
</body>
</html>
